package com.cloudlead.common.lang.log;

import com.cloudlead.common.lang.api.ErrorMeta;
import com.cloudlead.common.lang.security.SecurityUtils;
import com.cloudlead.common.lang.serialize.BeanSerializeException;
import com.cloudlead.common.lang.serialize.JSON;
import com.cloudlead.common.lang.utils.ExceptionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.Map;

/**
 * Created by dean on 2015/7/20.
 * <p>
 * 输出业务日志
 */
public class BizLog {
    private static final Logger LOGGER = LoggerFactory
            .getLogger("BUSINESS_LOG");

    public static void debug(Map<String, Object> msg) {
        log(LogLevel.DEBUG, msg, null);
    }

    public static void info(Map<String, Object> msg) {
        log(LogLevel.INFO, msg, null);
    }

    public static void warn(Map<String, Object> msg) {
        log(LogLevel.WARN, msg, null);
    }

    public static void error(Map<String, Object> msg, Throwable e) {
        log(LogLevel.ERROR, msg, e);
    }


    private static void log(LogLevel level, Map<String, Object> msg, Throwable e) {
        LogMetadata logMetadata = new LogMetadata(level, System.currentTimeMillis(), Thread.currentThread().getName(),
                SecurityUtils.getUsername(), MDC.get("action.name"), MDC.get("request.id"), msg);
        if (null != e) {
            ErrorMeta errorMeta = ExceptionHelper.toActionError(e);
            logMetadata.setError(errorMeta);
        }
        try {
            LOGGER.debug(JSON.toString(logMetadata));
        } catch (BeanSerializeException bse) {
            e.printStackTrace();
            //ignore
        }
    }

}
